﻿namespace CleverCMS.Cms.Services.Infrastructure
{
    using MvcSiteMapProvider;
    using System;
    using System.Linq;
    using System.Collections.Generic;

    using Core.Infrastructure;

    public class MenusDymanicNodeProvider : DynamicNodeProviderBase
    {
        private MenuItemService     m_menuItemService;
        private readonly AppCache   m_appCache;

        public MenusDymanicNodeProvider()
        {
            this.m_appCache = new AppCache();
        }

        public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
        {
            if (m_appCache.Exists("AdminMenus"))
                return (List<DynamicNode>)m_appCache.Get("AdminMenus");

            m_menuItemService = IoC.Get<MenuItemService>();
            var nodes = new List<DynamicNode>();

            var categories = m_menuItemService.LoadMenues().ToList();
            foreach (var category in categories)
            {
                var categoryNode = new DynamicNode
                {
                    Key = "menus_" + Guid.NewGuid() + "_" + category.Id,
                    Title = category.Description
                };
                categoryNode.RouteValues.Add("id", category.Id);
                categoryNode.Action = "List";
                categoryNode.Controller = "MenuItem";
                categoryNode.Area = "CleverCms.Admin";
                nodes.Add(categoryNode);

                if (m_menuItemService.LoadAllMenuItems().Any(x => x.MenuId == category.Id))
                {
                    var menuItems = m_menuItemService.LoadAllMenuItems().Where(x => x.MenuId == category.Id).ToList();
                    foreach (var menuItem in menuItems)
                    {
                        var menuItemNode = new DynamicNode
                        {
                            Key = "menuItem_" + Guid.NewGuid() + "_" + menuItem.Id,
                            Title = menuItem.Title
                        };
                        menuItemNode.RouteValues.Add("id", menuItem.Id);
                        menuItemNode.ParentKey = categoryNode.Key;
                        menuItemNode.Action = "Edit";
                        menuItemNode.Controller = "MenuItem";
                        menuItemNode.Area = "CleverCms.Admin";
                        nodes.Add(menuItemNode);
                    }
                }
            }

            m_appCache.Add("AdminMenus", nodes);
            return nodes;
        }
    }
}
